package com.ruoyi.baseInfo.service.Impl;

import com.ruoyi.baseInfo.domain.ClientsInfo;
import com.ruoyi.baseInfo.mapper.ClientsInfoMapper;
import com.ruoyi.baseInfo.service.ClientsInfoService;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class ClientsInfoServiceImpl implements ClientsInfoService {
    @Autowired(required = false)
    ClientsInfoMapper clientsInfoMapper;

    @Autowired(required = false)
    SysDeptServiceImpl sysDeptServiceImpl;
    /**
     * 查询客户基本信息列表
     * @param clientsInfo 查询参数
     * @return 结果
     */
    @Override
    public List<ClientsInfo> selectClientList(ClientsInfo clientsInfo) {
        return clientsInfoMapper.getClientList(clientsInfo);
    }

    /**
     * 根据ID查询所有子公司（正常状态）
     *
     * @param companyId 公司ID
     * @return 子公司数
     */
    @Override
    public int selectNormalChildrenById(Long companyId) {
        return clientsInfoMapper.selectNormalChildrenById(companyId);
    }

    /**
    * 校验公司名称是否唯一
    *
    * @param clientsInfo 公司信息
    * @return 结果
    */
    @Override
    public String checkCompanyNameUnique(ClientsInfo clientsInfo) {
        Long companyId  = StringUtils.isNull(clientsInfo.getCompanyId())?-1L:clientsInfo.getCompanyId();
        ClientsInfo info = clientsInfoMapper.checkCompanyNameUnique(clientsInfo.getCompanyName(),clientsInfo.getParentId());
        if (StringUtils.isNotNull(info) && info.getCompanyId().longValue() != companyId.longValue()){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
    /**
     * 校验企业是否有数据权限
     *
     * @param companyId 公司id
     */
    @Override
    public void checkClientDataScope(Long companyId) {
    if (!SysUser.isAdmin(SecurityUtils.getUserId())){
        ClientsInfo clientsInfo = new ClientsInfo();
        clientsInfo.setCompanyId(companyId);
        List<ClientsInfo> clientsInfos = SpringUtils.getAopProxy(this).selectClientList(clientsInfo);
        if (StringUtils.isEmpty(clientsInfos)){
            throw new ServiceException("没有访问权限");
        }
    }
    }
    /**
     * 根据Id查询信息
     *
     */
    @Override
    public ClientsInfo selectCompanyById(Long companyId) {
        return clientsInfoMapper.selectClientById(companyId);
    }

    /**
     * 新增保存企业信息
     *
     * @param clientsInfo 企业信息
     * @return 结果
     */
    @Override
    public int insertClient(ClientsInfo clientsInfo) {
        ClientsInfo info = clientsInfoMapper.selectClientById(clientsInfo.getParentId());
        clientsInfo.setAncestors(info.getAncestors() + "," + clientsInfo.getParentId());
        return clientsInfoMapper.insertClient(clientsInfo);
    }

    /**
     * 是否存在子节点
     *
     * @param companyId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildById(Long companyId)
    {
        int result = clientsInfoMapper.hasChildById(companyId);
        return result > 0;
    }

    /**
     * 删除企业信息
     *
     * @param companyId 公司ID
     * @return 结果
     */

    @Override
    public int deleteClientById(Long companyId) {
        return clientsInfoMapper.deleteClientById(companyId);
    }

    /**
     * 更改企业信息
     *
     * @param clientsInfo 公司ID
     * @return 结果
     */
    @Override
    public int updateClient(ClientsInfo clientsInfo) {
        ClientsInfo newParentClient = clientsInfoMapper.selectClientById(clientsInfo.getParentId());
        ClientsInfo oldClient = clientsInfoMapper.selectClientById(clientsInfo.getCompanyId());
        if (StringUtils.isNotNull(newParentClient)&&StringUtils.isNotNull(oldClient)){
            String newAncestors = newParentClient.getAncestors()+","+newParentClient.getCompanyId();
            String oldAncestors = oldClient.getAncestors();
            clientsInfo.setAncestors(newAncestors);
            updateChildren(clientsInfo.getCompanyId(),newAncestors,oldAncestors);
        }
        int result = clientsInfoMapper.updateClient(clientsInfo);
        if (UserConstants.NORMAL.equals(clientsInfo.getType()) && StringUtils.isNotNull(clientsInfo.getAncestors()) && !StringUtils.equals("0",clientsInfo.getAncestors())){
            // 如果该公司是启用状态，则启用该公司的所有上级公司
            updateParent(clientsInfo);
        }
        return result;
    }

    /**
     * 修改该公司的父级公司状态
     *
     * @param clientsInfo 当前公司
     */
    public void updateParent(ClientsInfo clientsInfo){
        String ancestors = clientsInfo.getAncestors();
        Long[] companyIds = Convert.toLongArray(ancestors);
        clientsInfoMapper.updateClientType(companyIds);
    }

    /**
     * 修改子元素关系
     *
     * @param companyId 被修改的公司ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateChildren (Long companyId, String newAncestors, String oldAncestors){
    List<ClientsInfo> children = clientsInfoMapper.selectChildrenById(companyId);
        for (ClientsInfo child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors,newAncestors));
        }
        if (children.size()>0){
            clientsInfoMapper.updateChildren(children);
        }
    }

}
